#pragma once

/*
Boost Software License - Version 1.0 - August 17th, 2003

Permission is hereby granted, free of charge, to any person or organization
obtaining a copy of the software and accompanying documentation covered by
this license (the "Software") to use, reproduce, display, distribute,
execute, and transmit the Software, and to prepare derivative works of the
Software, and to permit third-parties to whom the Software is furnished to
do so, all subject to the following:

The copyright notices in the Software and this entire statement, including
the above license grant, this restriction and the following disclaimer,
must be included in all copies of the Software, in whole or in part, and
all derivative works of the Software, unless such copies or derivative
works are solely in the form of machine-executable object code generated by
a source language processor.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/

#ifndef IntrusivePointer_h
#define IntrusivePointer_h

#include <stddef.h>

namespace fusion
{
    template <class T>
    class _NoDirectAddRefRelease : public T
    {
        // This wrapper is provided so Ref<> (below) will not allow 
        // clients to directly call AddRef() and Release()

        // A couple gotchas:
        //  if you get a compile error about "base class destructor is 
        //    inaccessible", make your destructor protected. If it's private, 
        //    the compiler can't make a default constructor for this object
        //  if you have an error about "cannot access private method" pertaining
        //    to AddRef() or Release(), then quit using SAFE_RELEASE() or 
        //    directly calling them

    private:
        virtual long AddRef() const = 0;
        virtual long Release() const = 0;
    };

    template<class T>
    class Ref
    {
    private:
        typedef Ref this_type;

    public:

        typedef T element_type;

        Ref(): p_(0)
        {
        }

        Ref(T* p, bool add_ref = true): p_(p)
        {
            if (p_ != 0 && add_ref) { p_->AddRef(); }
        }

        template<class U> Ref(Ref<U> const& rhs): p_(rhs.get())
        {
            if (p_ != 0) { p_->AddRef(); }
        }

        Ref(Ref const& rhs): p_(rhs.p_)
        {
            if (p_ != 0) { p_->AddRef(); }
        }

        ~Ref()
        {
            if (p_ != 0) { p_->Release(); }
        }

        template<class U> Ref<U> StaticCast() { return Ref<U>(static_cast<U*>(p_)); }
        template<class U> Ref<const U> StaticCast() const { return Ref<const U>(static_cast<const U*>(p_)); }

        template<class U> Ref& operator=(Ref<U> const& rhs)
        {
            if (*this != rhs)
            {
                this_type(rhs).swap(*this);
            }
            return *this;
        }

        Ref& operator=(Ref const& rhs)
        {
            if (*this != rhs)
            {
                this_type(rhs).swap(*this);
            }
            return *this;
        }

        Ref& operator=(T* rhs)
        {
            if (*this != rhs)
            {
                this_type(rhs).swap(*this);
            }
            return *this;
        }

        T* get() const
        {
            return p_;
        }

        T& operator*() const
        {
            return *p_;
        }

        operator T* () const
        {
            return get();
        }

        _NoDirectAddRefRelease<T>* operator->() const
        {
            return (_NoDirectAddRefRelease<T>*)p_;
        }

#ifndef __LP64__
        /* fix warning: ambiguous function overloading
         * ex: const Ref< Controller<Type> >& value
         * if (value == NULL) { ... }
         * candidate 1: template<class T> inline bool operator==(Ref<T> const& a, int b)
         * candidate 2: operator==(int, long int) <built-in> (value is converted to bool which is converted to int)
         * TODO: safe bool idiom to prevent evil cast to int
         */
        operator bool () const
        {
            return p_ != 0;
        }
#endif

        bool operator! () const
        {
            return p_ == 0;
        }

        void swap(Ref& rhs)
        {
            T* tmp = p_;
            p_ = rhs.p_;
            rhs.p_ = tmp;
        }

        void reset()
        {
            this_type().swap(*this);
        }

    private:

        T* p_;
    };

    template<class T, class U> inline bool operator==(Ref<T> const& a, Ref<U> const& b)
    {
        return a.get() == b.get();
    }

    template<class T, class U> inline bool operator!=(Ref<T> const& a, Ref<U> const& b)
    {
        return a.get() != b.get();
    }

    template<class T, class U> inline bool operator==(Ref<T> const& a, U* b)
    {
        return a.get() == b;
    }

    template<class T, class U> inline bool operator!=(Ref<T> const& a, U* b)
    {
        return a.get() != b;
    }

    template<class T> inline bool operator==(Ref<T> const& a, int b)   // NULL is an int.  Curse you, C++!
    {
        //ASSERT(reinterpret_cast<T*>(b) == NULL);  // This should only be used for comparing to NULL
        return a == reinterpret_cast<T*>(b);
    }

    template<class T> inline bool operator!=(Ref<T> const& a, int b)   // NULL is an int.
    {
        ASSERT(reinterpret_cast<T*>(b) == NULL);  // This should only be used for comparing to NULL
        return a != reinterpret_cast<T*>(b);
    }

    template<class T, class U> inline bool operator==(T* a, Ref<U> const& b)
    {
        return a == b.get();
    }

    template<class T, class U> inline bool operator!=(T* a, Ref<U> const& b)
    {
        return a != b.get();
    }

#if __GNUC__ == 2 && __GNUC_MINOR__ <= 96

    // Resolve the ambiguity between our op!= and the one in rel_ops

    template<class T> inline bool operator!=(Ref<T> const& a, Ref<T> const& b)
    {
        return a.get() != b.get();
    }

#endif

    template<class T> void swap(Ref<T> & lhs, Ref<T> & rhs)
    {
        lhs.swap(rhs);
    }

    // mem_fn support

    template<class T> T* get_pointer(Ref<T> const& p)
    {
        return p.get();
    }

    template<class T, class U> Ref<T> static_pointer_cast(Ref<U> const& p)
    {
        return static_cast<T*>(p.get());
    }

    template<class T, class U> Ref<T> const_pointer_cast(Ref<U> const& p)
    {
        return const_cast<T*>(p.get());
    }

    template<class T, class U> Ref<T> dynamic_pointer_cast(Ref<U> const& p)
    {
        return dynamic_cast<T*>(p.get());
    }
}

#endif // IntrusivePointer_h
